const axios = require('axios');
const { v4: uuidv4 } = require('uuid');

// TTSServResponse equivalent in Node.js
function parseResponse(response) {
    const { reqid, code, Message, operation, sequence, data } = response;
    return {
        reqid,
        code,
        message: Message,
        operation,
        sequence,
        data
    };
}

async function httpPost(url, headers, body, timeout) {
    try {
        const response = await axios.post(url, body, {
            headers: headers,
            timeout: timeout
        });
        return response.data;
    } catch (error) {
        console.error('HTTP POST request failed:', error.message);
        throw error;
    }
}

async function synthesis(text) {
    const reqID = uuidv4();
    console.log(reqID)
    const params = {
        app: {
            appid: "2558394233",  // 填写平台申请的appid
            token: "xlGafQqqlwGdnX56oXUiw7zKXL6HPmwU",  // token 不生效，使用默认值
            cluster: "volcano_tts"  // 填写平台上显示的集群名称
        },
        user: {
            uid: reqID  // 可选，填写用户的真实 ID 以便问题定位
        },
        audio: {
            voice_type: "zh_male_jingqiangkanye_moon_bigtts",  // 填写选中的音色代号
            encoding: "wav",
            speed_ratio: 1.0,
            volume_ratio: 1.0,
            pitch_ratio: 1.0
        },
        request: {
            reqid: reqID,
            text: text,
            text_type: "plain",
            operation: "query"
        }
    };

    const headers = {
        "Content-Type": "application/json",
        "Authorization": `Bearer;xlGafQqqlwGdnX56oXUiw7zKXL6HPmwU`  // bearerToken 为 saas 平台对应的接入认证中的 Token
    };

    // URL 查看上方第四点: 4.并发合成接口(POST)
    const url = "https://openspeech.bytedance.com/api/v1/tts";
    const timeout = 30000;  // 30 秒超时

    try {
        const response = await httpPost(url, headers, JSON.stringify(params), timeout);
        console.log('Response body:', response);

        const respJSON = parseResponse(response);
        const code = respJSON.code;

        if (code !== 3000) {
            console.error('Response code error:', code);
            throw new Error('Response code failed');
        }

        const audio = Buffer.from(respJSON.data, 'base64');
        return audio;
    } catch (error) {
        console.error('Synthesis failed:', error.message);
        throw error;
    }
}

(async () => {
    const text = "字节跳动语音合成";
    try {
        const audio = await synthesis(text);
        
        console.log(`Got audio successfully, length: ${audio.length} bytes`);
    } catch (error) {
        console.error('Error in synthesis process:', error.message);
    }
})();


